import React, { Component, createRef } from 'react'
import PropTypes from 'prop-types'

export default class Header extends Component {
  constructor() {
    super()
    this.inputRef = createRef()
  }
  static propTypes = {
    placeholder: PropTypes.string.isRequired,
    click: PropTypes.func
  }
  static defaultProps = {
    placeholder: '请输入您的任务名称，按回车键确认'
  }
  render() {
    const { placeholder } = this.props
    return (
      <div>
        <div className="form-group">
          <input
            type="text"
            className="form-control"
            ref={this.inputRef}
            placeholder={placeholder}
            onKeyUp={(e) => this.handleAddTodos(e)}
          />
        </div>
      </div>
    )
  }

  handleAddTodos(e) {
    // console.log(e)
    if (e.keyCode !== 13) {
      // alert('请输入代办事项')
      return
    }
    if (e.target.value === '') {
      return alert('请输入代办事项')
    }
    // 获取到输入的值并包装成需要的数据传给父组件
    this.props.click({
      id: Date.now(),
      title: this.inputRef.current.value,
      completed: false
    })
    // 清空
    this.inputRef.current.value = ''
    // 自动获取焦点
    this.inputRef.current.focus()
  }
}
